import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import {Badge, Button, Card, Checkbox, Col, Divider, Form, Input, Menu, Modal, Radio, Row, Select, Tree,} from 'antd';
import TableList from '@/components/TableList';
import styles from '../search.less';

const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
const RadioGroup = Radio.Group;
const {TreeNode} = Tree;
const DirectoryTree = Tree.DirectoryTree;
const statusMap = ['success', 'error'];
const status = ['启用', '禁用'];

const CreateForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    addDataFn,
    updateFn,
    handleModalVisible,
    text,
    orgTreeData,
    setUsercode,
    userCode,
    disableValue,
    disableCopy,
    saveChecked,
    copyChecked,
    printChecked,
    onReadonlyEditRight,
  } = props;
  const handleReadEdit = (e) => {
    onReadonlyEditRight(e)
  }
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      console.info("text1:" + text);
      console.info("userCode:" + userCode);
      if (!text && !userCode) {
        Modal.warning({title: '请选择组织树'});
        return;
      }
      const jurisdiction = fieldsValue.jurisdiction;
      const obj = {}
      jurisdiction && jurisdiction.length && jurisdiction.map((v) => {
        if (v == 2) {
          obj.saveAsRight = 0
        }
        if (v == 3) {
          obj.copyRight = 0
        }
        if (v == 4) {
          obj.printRight = 0
        }
      })

      if (text) {
        updateFn(Object.assign(obj, fieldsValue), text)
      } else {
        addDataFn(Object.assign(obj, fieldsValue));
      }
    });
  };
  const onSelect = (info, e) => {
    const userCode = e.node.props.id;
    setUsercode(userCode)
  }

  const loop = data => data.map((item) => {
    if (item.children) {
      return (
        <TreeNode key={item.id} title={item.orgName} {...item}>
          {loop(item.children || [])}
        </TreeNode>
      );
    }
    return <TreeNode key={item.id} title={item.orgName} {...item}/>;
  });

  const defaultId = text && text.userCode + '';

  const initialValue = [];
  if (text && text.userCode) {
    if (text.saveAsRight == 0) {
      initialValue.push(2)
    }
    if (text.copyRight == 0) {
      initialValue.push(3)
    }
    if (text.printRight == 0) {
      initialValue.push(4)
    }
  }

  return (
    <Modal
      destroyOnClose
      width={800}
      title={text ? '编辑权限配置' : '新增权限配置'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <Form>
        <Row gutter={16}>
          <FormItem labelCol={{span: 4}} wrapperCol={{span: 18}} label="编辑权限：">
            {form.getFieldDecorator('readonlyEditRight',
              {rules: [{required: true, message: '请选择编辑权限'}], initialValue: text && text.readonlyEditRight})(
              <RadioGroup onChange={handleReadEdit}>
                <Radio value={0}>只读</Radio>
                <Radio value={1}>编辑</Radio>
              </RadioGroup>
            )}
          </FormItem>

          <FormItem labelCol={{span: 4}} wrapperCol={{span: 18}} label="权限操作：">
            {form.getFieldDecorator('jurisdiction', {initialValue})(
              <CheckboxGroup>
                <Checkbox checked={copyChecked} key="copyKey" disabled={disableCopy} value={3}>禁止复制</Checkbox>
                <Checkbox checked={saveChecked} key="saveKey" disabled={disableValue} value={2}>禁止另存</Checkbox>
                <Checkbox checked={printChecked} key="printKey" disabled={disableValue} value={4}>禁止打印</Checkbox>
              </CheckboxGroup>
            )}
          </FormItem>

          <FormItem labelCol={{span: 4}} wrapperCol={{span: 18}} label="状态"
                    style={{display: text == null ? 'none' : 'block',}}>
            {form.getFieldDecorator('status', {
              initialValue: text && text.status
            })(<Radio.Group>
              <Radio value={0}>
                启用
              </Radio>
              <Radio value={1}>
                禁用
              </Radio>
            </Radio.Group>)}
          </FormItem>


          {!text ? <Col md={24}>
            <FormItem labelCol={{span: 4}} wrapperCol={{span: 18}} label="组织结构">
              <DirectoryTree
                multiple
                onSelect={onSelect}
                defaultExpandedKeys={[defaultId]}
                defaultSelectedKeys={[defaultId]}
              >
                {
                  orgTreeData && orgTreeData.length && loop(orgTreeData || [])
                }
              </DirectoryTree>
            </FormItem>
          </Col> : null}
        </Row>
      </Form>
    </Modal>
  );
});

/* eslint react/no-multi-comp:0 */
@connect(({editOrg, loading}) => ({
  editOrg,
  loading: loading.models.editOrg,
}))


@Form.create()
class editOrg extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
    text: {},
    orgTreeData: [],
    userCode: '',
    //权限编辑
    disableValue: false,
    disableCopy: false,
    saveChecked: false,
    copyChecked: false,
    printChecked: false,
  };

  columns = [
    {
      title: '组织名称',
      dataIndex: 'name',
    },
    {
      title: '上级组织',
      dataIndex: 'parentName',

    },
    {
      title: '编辑权限',
      dataIndex: 'rightStr',

    },
    {
      title: '状态',
      dataIndex: 'status',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]}/>;
      },
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true, text)}>编辑</a>
          <Divider type="vertical"/>
          {/* <Popconfirm title="是否要删除此行？" onConfirm={() => this.handleDeleteData(text.id)}>
            <a>删除</a>
          </Popconfirm>*/}

          <a onClick={() => this.handleDeleteData(text.id)}>删除</a>
        </Fragment>
      ),
    },
  ];
  handleDeleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.deleteItem(id),
    });
  };

  setUsercode = (v) => {
    this.setState({
      userCode: v,
    })
  }

  batchDelete = (rows = []) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.handleDeleteData(ids); //批量删除
  };

  // 删除方法
  deleteItem(id) {
    const {dispatch} = this.props;
    dispatch({
      type: 'editOrg/remove',
      payload: {id},
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({
            title: res.msg,
          });
          this.pageList();
          this.setState({selectedRows: []})
        } else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
  }

  // 分页查询列表
  pageList(data, pageSize = 10, pageNum = 0) {
    const {dispatch} = this.props;
    const values = {
      name: data && data.name || '',
      readonlyEditRight: data && data.readonlyEditRight,
      copyRight: data && data.copyRight,
      saveAsRight: data && data.saveAsRight,
      printRight: data && data.printRight,
      userType: 2,
      pageSize: pageSize, //分页每页条数
      pageNum: pageNum, //分页页码
    };
    dispatch({
      type: 'editOrg/queryList',
      payload: values,
    });
  }

  componentDidMount() {
    this.pageList();
    this.orgUserTree();//组织树请求
  }

  orgUserTree() {
    const {dispatch} = this.props;
    dispatch({
      type: 'editOrg/orgUserTree',
      callback: (res) => {
        if (res.result == "ok") {
          this.setState({
            orgTreeData: res.data.dataList,
          })
        } else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const {dispatch, form} = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const obj = {};
      if (fieldsValue.authority == "0") {
        obj.readonlyEditRight = 0;
      } else if (fieldsValue.authority == "1") {
        obj.readonlyEditRight = 1;
      }
      else if (fieldsValue.authority == "2") {
        obj.saveAsRight = 0;
      }
      else if (fieldsValue.authority == "3") {
        obj.copyRight = 0;
      }
      else if (fieldsValue.authority == "4") {
        obj.printRight = 0;
      } else {
        obj.readonlyEditRight = '';
        obj.saveAsRight = '';
        obj.copyRight = '';
        obj.printRight = '';
      }
      this.pageList(Object.assign(fieldsValue, obj));
      this.setState({
        formValues: Object.assign(fieldsValue, obj),
      })
    });
  };
// 新增弹框的显示和隐藏
  handleModalVisible = (flag, text) => {
    this.setState({
      modalVisible: !!flag,
      text: text,
      userCode: text && text.userCode ? text.userCode : ''
    });
    if (flag && text) {
      if (text.readonlyEditRight == 0) {
        this.setState({
          disableValue: true,
          disableCopy: false,
        })
      } else {
        this.setState({
          disableValue: false,
          disableCopy: true,
        })
      }
    }
  };

  // 更新接口
  updateFn = (fields, text) => {
    const {dispatch} = this.props;
    // const { userCode } = this.state;
    const params = {
      userType: 2,
      // userCode: userCode?userCode:text.userCode,
      id: text.id,
      status: fields.status,
      readonlyEditRight: fields.readonlyEditRight,
      copyRight: fields.readonlyEditRight == 0 ? fields.copyRight : '',
      saveAsRight: fields.readonlyEditRight == 1 ? fields.saveAsRight : '',
      printRight: fields.readonlyEditRight == 1 ? fields.printRight : '',
    }
    dispatch({
      type: 'editOrg/update',
      payload: params,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({
            title: res.msg,
          });
          this.pageList();
        } else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
    this.handleModalVisible();
  };

  // 增加接口
  addDataFn = (fields) => {
    const {dispatch} = this.props;
    const {userCode} = this.state;
    const params = {
      userType: 2,
      userCode,
      readonlyEditRight: fields.readonlyEditRight,
      copyRight: fields.readonlyEditRight == 0 ? fields.copyRight : '',
      saveAsRight: fields.readonlyEditRight == 1 ? fields.saveAsRight : '',
      printRight: fields.readonlyEditRight == 1 ? fields.printRight : '',
    }
    dispatch({
      type: 'editOrg/add',
      payload: params,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({
            title: res.msg,
          });
          this.pageList();
        } else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
    this.handleModalVisible();
  };

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="组织名称">
              {getFieldDecorator('name')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="编辑权限">
              {getFieldDecorator('authority')(<Select placeholder="请选择" style={{width: '100%'}}>
                <Option value="5">全部</Option>
                <Option value="0">只读</Option>
                <Option value="1">编辑</Option>
                <Option value="2">禁止另存为</Option>
                <Option value="3">禁止复制</Option>
                <Option value="4">禁止打印</Option>
              </Select>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const {expandForm} = this.state;
    return expandForm ? this.renderSimpleForm() : this.renderSimpleForm();
  }

  handleStandardTableChange(pagination, filters, sorter) {
    const {formValues} = this.state;
    // 分页请求
    this.pageList(formValues, pagination.pageSize, pagination.current - 1);
  }

  onReadonlyEditRight = e => {
    const value = e.target.value;
    if (value == 0) {
      this.setState({
        // rightDo: [2,4],

        saveChecked: true,
        copyChecked: false,
        printChecked: true,
        disableValue: true,
        disableCopy: false,
      })
    } else {
      this.setState({
        // rightDo: [],

        saveChecked: false,
        copyChecked: false,
        printChecked: false,
        disableValue: false,
        disableCopy: true,
      })
    }

  }

  render() {
    const {
      editOrg: {data},
      loading,
    } = this.props;
    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      stepFormValues,
      text,
      orgTreeData,
      userCode,
      disableValue,
      disableCopy,
      saveChecked,
      copyChecked,
      printChecked,
    } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
      </Menu>
    );
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      addDataFn: this.addDataFn,
      updateFn: this.updateFn,
      setUsercode: this.setUsercode,
      onReadonlyEditRight: this.onReadonlyEditRight,
    };

    return (
      <Card bordered={false}>
        <CreateForm
          {...parentMethods}
          modalVisible={modalVisible}
          text={text}
          orgTreeData={orgTreeData}
          userCode={userCode}
          saveChecked={saveChecked}
          copyChecked={copyChecked}
          printChecked={printChecked}
          disableValue={disableValue}
          disableCopy={disableCopy}
        />
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
              新增
            </Button>
            {selectedRows.length > 0 && (
              <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
            )}
          </div>
          <TableList
            className={styles.tdPadding}
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange.bind(this)}
            rowKey={record => record.id}
          />
        </div>
      </Card>
    );
  }
}

export default editOrg;
